package cn.dida.core;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

import cn.dida.exception.BizzException;
import cn.dida.model.UserSession;
import cn.dida.util.AESEncryptor;

import com.alibaba.fastjson.JSONObject;

/**
 * 安全拦截器，检查登录状态等
 *
 * @author weiwei1
 */
public class LoginCheckInterceptor extends HandlerInterceptorAdapter {
//	private Log log = LogFactory.getLog(SecurityCheckInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie passportCookie = WebUtils.getCookie(request, Constants.PASSPORT_KEY);
        if (passportCookie == null || StringUtils.isEmpty(passportCookie.getValue())) {
            handleNotLogin(request, response);
            return false;
        } else {
            try {
                String passport = String.valueOf(AESEncryptor.decryptor(passportCookie.getValue()));
                UserSession session = JSONObject.parseObject(passport, UserSession.class);
                request.setAttribute(Constants.USER_SESSION_KEY, session);

/*                // 把usersession放入线程变量容器
                ThreadLocalContainer.setUserSession(session);*/

            } catch (Exception e) {
                handleNotLogin(request, response);
                return false;
            }
        }
        return true;
    }

    private void handleNotLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            throw new BizzException(BizzException.error_code_require_login, "您的登录信息已过期，请重新登录");
        }
        response.sendRedirect("/login");
    }
}
